Fork me on GitHub

promise对象封装ajax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function getJson(url) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);

xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
resolve(this.responseText, this)
} else {
let resJson = {
code: this.status,
response: this.response
}
reject(resJson, this)
}
}

}
xhr.send();
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  function postJson(url, data) {
return new Promise((resole, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
resolve(JSON.parse(this.responseText), this)
} else {
let resJson = {
code: this.status,
response: this.response
}
}
}
}
xhr.send(JSON.stringify(data))
})
}
1
2
3
4
5
6
7
getJSON('/api/v1/xxx')    // => 这里面是就try
.catch( error => {
// dosomething // => 这里就是catch到了error,如果处理error以及返还合适的值
})
.then( value => {
// dosomething // 这里就是final
})

本文标题:promise对象封装ajax

文章作者:tongtong

发布时间:2018年02月28日 - 00:02

最后更新:2019年03月15日 - 11:03

原始链接:https://ilove-coding.github.io/2018/02/28/[待完成]从ajax到promise封装/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!
-------------本文结束-------------